<template>
  <div class="settings-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height:60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="hAdd()"
              >新增角色</el-button>
            </el-row>
            <!-- 表格 -->
            <el-table :data="rolesList">
              <el-table-column label="序号" width="120" type="index" />
              <el-table-column label="角色名称" width="240" prop="name" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template #default="{row}">
                  <el-button size="small" type="success" @click="hAssign(row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="hEdit(row)">编辑</el-button>
                  <el-button size="small" type="danger" @click="hDel(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <el-row type="flex" justify="center" align="middle" style="height: 60px">
              <!-- 分页组件 -->
              <el-pagination
                :current-page="pageParams.page"
                :page-sizes="[2, 3, 5, 10]"
                :page-size="pageParams.pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <!-- 弹框 -->
      <!-- 新增员工弹框 -->
      <el-dialog
        :title="isEdit?'编辑':'添加'"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :visible.sync="showDialog"
        @close="hClose()"
      >
        <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="100px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" />
          </el-form-item>
          <el-form-item label="角色描述">
            <el-input v-model="roleForm.description" />
          </el-form-item>
        </el-form>
        <!-- 底部 -->
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small" @click="showDialog=false">取消</el-button>
            <el-button size="small" type="primary" @click="hSubmit">确定</el-button>
          </el-col>
        </el-row>
      </el-dialog>
      <!-- 角色分配权限弹出框 -->
      <el-dialog
        :visible.sync="showDialogAssign"
        title="角色分配权限"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
      >
        <assignPermission v-if="showDialogAssign" :cur-id="curId" @success="hSuccess" @close="showDialogAssign=false" />
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { getRoles, deleteRole, addRole, updateRole } from '@/api/setting'
import assignPermission from './assignPermission'
export default {
  components: {
    assignPermission
  },
  data() {
    return {
      rolesList: [],
      pageParams: {
        page: 1, // 当前页码值
        pagesize: 2 // 每页显示多少条数据
      },
      total: 0, // 总条数
      showDialog: false, // 添加角色弹出框
      roleForm: {
        name: '',
        description: ''
      },
      // 校验规则
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }]
      },
      isEdit: false, // false为添加 true为编辑
      showDialogAssign: false, // 角色分配权限弹出框
      curId: ''
    }
  },
  created() {
    this.loadRoles()
  },
  methods: {
    // 获取角色列表
    async loadRoles() {
      try {
        const res = await getRoles(this.pageParams)
        console.log('请求角色列表成功', res)
        this.rolesList = res.data.rows
        this.total = res.data.total
      } catch (error) {
        console.log('请求角色列表失败,原因是', error)
      }
    },
    // 用户点击了页码
    handleSizeChange(val) {
      this.pageParams.page = 1
      this.pageParams.pagesize = val
      this.loadRoles()
    },
    // 用户切换了每页显示条数
    handleCurrentChange(val) {
      this.pageParams.page = val
      this.loadRoles()
    },
    // 删除角色 -> 询问框
    hDel(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 确认删除
        this.doDel(id)
      }).catch(() => {
        // 取消删除
      })
    },

    // 实现删除
    async doDel(id) {
      try {
        const res = await deleteRole(id)
        console.log('删除角色成功', res)
        this.$message.success('删除成功')
        // 分页处理
        if (this.rolesList.length === 1) {
          this.pageParams.page--
          if (this.rolesList.page <= 1) {
            this.pageParams.page = 1
          }
        }
        this.loadRoles()
      } catch (error) {
        console.log('删除角色失败,原因是', error)
      }
    },
    // 添加
    hAdd() {
      this.showDialog = true
      this.isEdit = false
    },
    // 确认按钮 -> 兜底校验
    hSubmit() {
      this.$refs.roleForm.validate(valid => {
        if (!valid) return
        this.isEdit ? this.doEdit() : this.doAdd()
      })
    },
    // 实现添加
    async doAdd() {
      try {
        const res = await addRole(this.roleForm)
        console.log('添加角色成功', res)
        this.$message.success('添加成功')
        // 新增数据 页码更新
        this.total++
        this.pageParams.page = Math.ceil(this.total / this.pageParams.pagesize)
        this.loadRoles()
        this.showDialog = false
      } catch (error) {
        console.log('添加角色失败,原因是', error)
      }
    },
    // 编辑
    hEdit(row) {
      this.roleForm = { ...row } // 把当前的数据直接给表单
      this.showDialog = true // 显示弹层
      this.isEdit = true
    },
    // 实现编辑
    async doEdit() {
      try {
        const res = await updateRole(this.roleForm)
        console.log(res)
        this.loadRoles()

        this.$message.success('编辑成功')
        this.showDialog = false
      } catch (err) {
        console.log('编辑失败,原因是', err)
      }
    },
    // 弹层关闭事件 -> 重置表单
    hClose() {
      this.roleForm = {
        name: '',
        description: ''
      }
      this.$refs.roleForm.resetFields() // 清空验证规则
    },
    // 点击分配权限
    hAssign(id) {
      this.showDialogAssign = true
      this.curId = id
    },
    // 分配权限自定义事件
    hSuccess() {
      this.showDialogAssign = false
      this.loadRoles()
    }
  }
}
</script>

